package beans;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.Part;

import utils.FileUploadServlet;
import utils.Navigation;
import dto.CandidateDTO;
import dto.CitizenDTO;
import dto.PartyDTO;
import dto.SubscribeDTO;
import entitymanagers.PartyManager;
import entitymanagers.SubscribeManager;

@ManagedBean(name = "SubscribeBean")
@RequestScoped
public class SubscribeBean {
	
	@EJB
	private SubscribeManager subscribe;
	@EJB
	private PartyManager party;
	private String cv;
	private SubscribeDTO[] subRequests;
	private SubscribeDTO[] allSubs;
	private SubscribeDTO subDTO;
	private PartyDTO partyDTO;
	private CitizenDTO citDTO;
	private CandidateDTO candDTO;
	
	@ManagedProperty("#{param.partyID")
	private String partyID;
	
	public String addSubscribe() throws Exception{
		try{ 
			partyID = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("partyID");
			getPartyDTO().setPartyID(getPartyID());
			subDTO.setParty(partyDTO);
			subDTO.setCandidate(candDTO);
			
			candDTO.setCv(cv);
			subscribe.addSubscribe(subDTO);
			return Navigation.HOME + "?faces-redirect=true";
		}
		catch (Exception e){
			return "/error";
		}
	}

	private PartyDTO getPartyDTO() {
		if (partyDTO == null){
			partyDTO = new PartyDTO();
		}
		return partyDTO;
		
	}

	public String getPartyID() {
		if (partyID == null){
			return "";
		}
		return partyID;
	}
	public void setPartyID(String partyID) {
		if (this.partyID == null){
			this.partyID = partyID;
			getPartyDTO();
		}
	}
	
	public SubscribeDTO getSubscribeDTO(){
		if(subDTO == null){
			subDTO = new SubscribeDTO();
		}
		return subDTO;
	}
	
	public String toSubscribePage(){
		partyID = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("partyID");
		if (partyID==null){
			String message = "The request is not valid.";
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,message,null));
			
		}
		return "/user/Subscribe";
	}
	
	public CitizenDTO getCitizenDTO(){
		if (citDTO == null){
			citDTO = new CitizenDTO();
		}
		return citDTO;
	}
	
	//public Part getCV(){
		//return cv;
	//}
	public SubscribeDTO[] getSubscribes(){
		if (allSubs == null){
			allSubs = subscribe.getSubscribers();
		}
		return allSubs;
	}

}